<?php

namespace App\Console\Commands;

use App\Models\OnlineUser;
use Illuminate\Console\Command;

class UpdateOnlineDuration extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'online:update-duration';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '更新所有在线用户的在线时长';

    /**
     * Execute the console command.
     */
    public function handle()
    {
        $this->info('开始更新在线用户时长...');

        $count = 0;
        OnlineUser::whereNotNull('login_at')->chunk(100, function ($onlineUsers) use (&$count) {
            foreach ($onlineUsers as $onlineUser) {
                try {
                    $onlineUser->updateOnlineDuration();
                    $count++;
                } catch (\Exception $e) {
                    $this->error("更新用户 {$onlineUser->username} 的在线时长失败: " . $e->getMessage());
                }
            }
        });

        $this->info("成功更新 {$count} 个在线用户的时长");
        
        return Command::SUCCESS;
    }
}

